//
//  NetworkHander.m
//  UI19_网络封装(delegate回调)
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NetworkHander.h"

@implementation NetworkHander

// 通过NSURLSession实现网络请求.
- (void)networkHandlerJSONWithURL:(NSString *)urlString{
    
    // 将字符串进行转码(URL中不能含有中文等字符).
    NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // URL.
    NSURL *url = [NSURL URLWithString:temp];
    
    // Session.
    NSURLSession *session = [NSURLSession sharedSession];
    
    // add Task.
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data == nil) {
            
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程.
            
            NSError *errorJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
            
            if ([self.delegate respondsToSelector:@selector(handlerDidComplete:)]) {
            
                [self.delegate handlerDidComplete:result];
            }
        });
    }];
    
    [task resume];
}

+ (void)handlerJSONWithURL:(NSString *)urlString delegate:(id<NetworkHandlerDelegate>)delegate {
    
    NetworkHander *handler = [[NetworkHander alloc] init];
    
    handler.delegate = delegate;
    
    [handler networkHandlerJSONWithURL:urlString];
}






@end
